//
//  CJConsultBaseMenuViewController.m
//  CJHealthy01
//
//  谷瑞杰 on 16/7/11.
//  Copyright © 2016年 Alfred. All rights reserved.
//

#import "CJConsultBaseMenuViewController.h"
//#import "CJMyCollectionView.h"

static NSString * const ID = @"cell";
@interface CJConsultBaseMenuViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UIGestureRecognizerDelegate>

@property (nonatomic, weak) UICollectionView *collectionView;
@property (nonatomic, weak) UIScrollView *topView;
@property (nonatomic, weak) UIButton *selButton;
@property (nonatomic, strong) NSMutableArray *titleButtons;
@property (nonatomic, weak) UIView *underLineView;
@property (nonatomic, assign) BOOL isInitial;

@property (assign ,nonatomic) NSInteger shouDongValue;
@property (assign ,nonatomic) CGFloat offsetX;
@end

@implementation CJConsultBaseMenuViewController

- (NSMutableArray *)titleButtons
{
    if (_titleButtons == nil) {
        _titleButtons = [NSMutableArray array];
    }
    return _titleButtons;
}

// 显示在最外面的view,就是导航控制器栈顶控制器
// 导航条内容 是由栈顶控制器的navgaitonItem决定
- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    // 搭建底部view：UICollectionView
    [self setupBottomView];
    
    // 搭建顶部view: UIScollowView
    [self setupTopView];
    
    // iOS7之后，如果是导航控制器下scrollView,顶部都会添加64的额外滚动区域
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    //self.navigationController.interactivePopGestureRecognizer.delegate = self;

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (_isInitial == NO) {
        
        // 设置所有标题
        [self setupAllTitle];
        
        _shouDongValue = 8;
        _isInitial = YES;
    }
    
}
// 设置所有标题
- (void)setupAllTitle
{
    NSInteger count = self.childViewControllers.count;
    CGFloat btnW = kScreenWidth / count;
    CGFloat btnH = _topView.height;
    
    //NSLog(@"self.childViewControllers.count==%ld",count);
    CGFloat btnX = 0;
    for (int i = 0; i < count; i++) {
        UIButton *titleButton = [UIButton buttonWithType:UIButtonTypeCustom];
        btnX = i * btnW;
        titleButton.tag = i;
        titleButton.frame = CGRectMake(btnX, 0, btnW, btnH);
        NSString *title = [self.childViewControllers[i] title];
        //NSLog(@"%@",title);
        [titleButton setTitle:title forState:UIControlStateNormal];
        [titleButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [titleButton setTitleColor:GRJMainColor forState:UIControlStateSelected];

        // 设置标题字体
        titleButton.titleLabel.font = [UIFont systemFontOfSize:15];
        // 监听标题按钮点击
        [titleButton addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
        [_topView addSubview:titleButton];
        [self.titleButtons addObject:titleButton];
        
        // 默认选中第0个按钮
        if (i == self.selectIndexNum) {
            [self titleClick:titleButton];
            // 下划线宽度 = 按钮文字宽度
            // 下划线中心点的x = 按钮中心点x
            // 下划线的高度 = 2
            // 下划线的y = topView的height - 2
            // 添加下划线
            // 按钮的标题的宽度不会马上计算，只能手动计算文字宽度
            UIView *underLineView = [[UIView alloc] init];
            underLineView.backgroundColor = GRJMainColor;
            // 注意：设置中心点，一点要先设置尺寸
            underLineView.width = [title sizeWithFont:[UIFont systemFontOfSize:15]].width;
            underLineView.centerX = titleButton.centerX;
            
            underLineView.height = 2;
            underLineView.y = _topView.height - underLineView.height-4;
            [_topView addSubview:underLineView];
            _underLineView = underLineView;
        }
    }
}

#pragma mark - 点击标题就会调用
// UICollectionView不能再滚动完成的时候去添加对应的tableView,cell有循环利用，有可能显示其他子控制器View
// 不能再点击标题的时候，去拿到对应cell，往上面添加tableView（对应子控制器的view）
- (void)titleClick:(UIButton *)button
{
    NSInteger i = button.tag;
    // 1.选中按钮
    [self selButton:button];
    
    // 2.让collectionView滚动到对应位置,并不是马上滚动
    CGFloat offsetX = i * kScreenWidth;
    _collectionView.contentOffset = CGPointMake(offsetX, 0);
    
    _shouDongValue = 8;
    _offsetX = offsetX;
    /*
     问题：点击标题，拿不到cell，返回cell方法根本就没有调用
     分析：返回cell方法为什么没有调用 因为没有滚动
     即使滚动了 也拿不到，contentOffset 延迟 ，并不是马上滚动。
     */
}

#pragma mark - 选中按钮
- (void)selButton:(UIButton *)button
{
    _selButton.selected = NO;
    button.selected = YES;
    _selButton = button;
    
    // 移动下划线
    [UIView animateWithDuration:0.25 animations:^{
        
        _underLineView.centerX = button.centerX;
        _underLineView.width = button.titleLabel.width;
    }];
}

// 1.添加底部view 2.添加顶部view 3.让collevtionView展示cell 4.调整cell的尺寸 5.取消了顶部额外滚动区域

// 搭建顶部view: UIScollowView
- (void)setupTopView
{
    UIScrollView *topView = [[UIScrollView alloc] init];
    topView.layer.borderWidth = 1;
    topView.layer.borderColor = GRJColor(242, 242, 242).CGColor;
    
    topView.scrollsToTop = NO;
    _topView = topView;
//    topView.backgroundColor = [UIColor colorWithWhite:1 alpha:0.7];
    topView.backgroundColor = [UIColor whiteColor];
//    CGFloat topY = self.navigationController.navigationBarHidden? 20 : 64;
    CGFloat topY  = 0 ;
    CGFloat topH = 44;
    CGFloat topW = kScreenWidth;
    topView.frame = CGRectMake(0, topY, topW, topH);
    
//    topView.showsHorizontalScrollIndicator = NO;
//    
//    topView.contentSize = CGSizeMake((topW * 6 / 4.0), 0);
    [self.view addSubview:topView];
}

// 搭建底部view：UICollectionView；占据全屏
- (void)setupBottomView
{
    
    // 设置布局
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(kScreenWidth, kScreenHeight);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    
    
    // 指示器，cell间距，分页
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    collectionView.scrollsToTop = NO;
    _collectionView = collectionView;
    collectionView.backgroundColor = [UIColor whiteColor];
    collectionView.bounces = NO;
    collectionView.dataSource = self;
    collectionView.pagingEnabled = YES;
    collectionView.delegate = self;
    collectionView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:collectionView];
    
    //self.collectionView.bounces = NO;
    // 注册cell
    [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:ID];
}

#pragma mark - UICollectionViewDataSource
// 有多少个子控制器就有多少个cell
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
//    NSLog(@"%ld",self.childViewControllers.count);
    
    return self.childViewControllers.count;
}

// 只要有新的cell显示的时候才会调用
// 返回cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell =  [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    
    // 注意：一定要记得移除之前添加到cell上子控制器
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    // 3.把对应子控制器的view添加到对应的cell 的 contentView
    // 注意:一定要记得设置子控制器的view尺寸和位置
    UIViewController *vc = self.childViewControllers[indexPath.row];
    vc.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    [cell.contentView addSubview:vc.view];
    
//    cell.backgroundColor = GRJColor(arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256));
    
    return cell;
}

#pragma mark - UICollectionViewDelegate
// collectionView滚动完成就会调用
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSInteger i = scrollView.contentOffset.x / kScreenWidth;
    // 选中对应的标题
    
    [self selButton:self.titleButtons[i]];
}
//-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    NSLog(@"%ld",_shouDongValue);
//    if (_shouDongValue == 8) {
//        
//        
//    }else{
////        _shouDongValue = 0;
//        _collectionView.contentOffset = CGPointMake(_offsetX, 0);
//    }
//}

@end
